import Vue from "vue";
import axios from "axios";
import { ElLoading, ElMessage } from "element-plus";
const url = process.env.VUE_APP_BASE_API;

let loading = null; // 定义loading变量

// 开始 加载loading
const startLoading = () => {
  loading = ElLoading.service({
    lock: true,
    text: "加载中……",
    background: "rgba(0, 0, 0, 0.7)",
  });
};
// 结束 取消loading加载
const endLoading = () => {
  loading.close();
};

// 导出封装好的axios
export function request(config) {
  // 1、创建axios实例
  const instance = axios.create({
    baseURL: url,
    headers: {
      Authorization: sessionStorage.getItem("token"),
      "Content-Type": "application/json; charset=utf-8",
    },
  });
  // 2、axios的请求拦截器
  instance.interceptors.request.use(
    (config) => {
      // 配置请求头与token
      // config.headers.authorization = ''

      // startLoading()
      // if (localStorage.getItem('token')) {
      //     // config.headers = { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }
      //     config.headers.Authorization = localStorage.getItem('token')
      // }
      return config;
    },
    (err) => {
      return Promise.reject(err);
    }
  );
  // 3、axios的响应拦截器
  instance.interceptors.response.use(
    (res) => {
      // 根据code值提示
      const response = res.data;
      // if (res.code === 200) {

      // }
      if (response.code == 10) {
        router.push("login");
        ElMessage({
          message: response.msg,
          type: "error",
          duration: 5 * 1000,
        });
      }
      // 保证最少500毫秒的加载时间
      // setTimeout(() => {
      //     endLoading()
      // }, 500)
      return res.data;
    },
    (err) => {
      // setTimeout(() => {
      //     endLoading()
      // }, 500)
      ElMessage({
        message: "请求失败：" + err.msg,
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(err);
    }
  );

  return instance(config);
}
